package com.hejjon.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hejjon.core.domain.entity.BusinessAttr;
import com.hejjon.core.domain.entity.FeatureCategory;
import com.hejjon.core.enumer.DeleteFlagEnum;
import com.hejjon.core.enumer.FeatureFieldKindEnum;
import com.hejjon.core.enumer.FeatureKindEnum;
import com.hejjon.core.exception.BusinessException;
import com.hejjon.core.utils.StrUtil;
import com.hejjon.core.utils.TreeBuilder;
import com.hejjon.domain.vo.BusiAttrTreeNodeVO;
import com.hejjon.domain.vo.BusinessAttrVO;
import com.hejjon.domain.vo.FeatureFieldVO;
import com.hejjon.mapper.BusinessAttrMapper;
import com.hejjon.service.IBusinessAttrService;
import com.hejjon.service.IFeatureCategoryService;
import com.hejjon.service.IFeatureFieldService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: cs
 * @date: 2025-04-17 14:37:05
 * @since: 1.0
 */
@Service
public class BusinessAttrServiceImpl extends ServiceImpl<BusinessAttrMapper, BusinessAttr> implements IBusinessAttrService {


    @Resource
    private IFeatureCategoryService featureCategoryService;

    @Resource
    private BusinessAttrMapper businessAttrMapper;

    @Resource
    private IFeatureFieldService featureFieldService;

    @Override
    public boolean create(BusinessAttr ba) {
        if (StringUtils.isBlank(ba.getName())
                || StringUtils.isBlank(ba.getText())) {
            throw new BusinessException("名称或者显示名称不可为空");
        }
        ba.setId(StrUtil.getUUID());
        ba.setCreateBy("admin");
        ba.setCreateTime(LocalDateTime.now());
        ba.setDeleteFlag(DeleteFlagEnum.NO.getCode());
        return save(ba);
    }


    @Override
    public boolean update(BusinessAttr ba) {
        String id = ba.getId();
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException("业务属性ID为空!");
        }
        return updateById(ba);
    }

    @Override
    public List<BusinessAttrVO> listByCategoryId(String categoryId) {
        return baseMapper.selectByCategoryId(categoryId);
    }


    @Override
    public boolean exitByCategoryId(String categoryId) {
        Integer num = baseMapper.existByCategoryId(categoryId);
        return num != null && num > 0;
    }

    @Override
    public List<BusinessAttrVO> listByCategoryIds(List<String> categoryIdList) {
        List<String> ids = categoryIdList.stream()
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());
        return baseMapper.selectByCategoryIdList(ids);
    }

    @Override
    public List<BusiAttrTreeNodeVO> listTree(String featureId) {
        List<FeatureFieldVO> fieldVOList = featureFieldService.findByFeatureId(featureId);      // 当前特征已有的字段
        // 过滤出已经添加的来自业务属性的字段
        List<String> exitBusiAttrIdList = fieldVOList.stream().filter(o -> FeatureFieldKindEnum.busiAttr.name().equals(o.getKind())
                && StringUtils.isNotBlank(o.getBusiAttrId())).map(FeatureFieldVO::getBusiAttrId).collect(Collectors.toList());

        List<FeatureCategory> categoryList = featureCategoryService.findByKind(FeatureKindEnum.busiAttr.name());
        List<String> categoryIdList = categoryList.stream().map(FeatureCategory::getId).collect(Collectors.toList());
        List<BusinessAttrVO> businessAttrVOList = listByCategoryIds(categoryIdList);
        Map<String, List<BusinessAttrVO>> busiAttrMap = businessAttrVOList.stream()
                .collect(Collectors.groupingBy(BusinessAttrVO::getCategoryId));
        List<BusiAttrTreeNodeVO> treeNodeVOList = new ArrayList<>();

        for (FeatureCategory category : categoryList) {
            BusiAttrTreeNodeVO treeNodeVO = new BusiAttrTreeNodeVO();
            String categoryId = category.getId();
            treeNodeVO.setId(categoryId);
            treeNodeVO.setName(category.getName());
            treeNodeVO.setText(category.getName());
            treeNodeVO.setLabel(category.getName());
            treeNodeVO.setType(FeatureKindEnum.category.name());
            treeNodeVO.setParentId(category.getParentId());
            treeNodeVOList.add(treeNodeVO);

            if (busiAttrMap.containsKey(categoryId)) {
                List<BusinessAttrVO> businessAttrVOS = busiAttrMap.get(categoryId);
                for (BusinessAttrVO businessAttrVO : businessAttrVOS) {
                    BusiAttrTreeNodeVO child = new BusiAttrTreeNodeVO();
                    String id = businessAttrVO.getId();
                    child.setId(id);
                    child.setName(businessAttrVO.getName());
                    child.setText(businessAttrVO.getText());
                    child.setLabel(businessAttrVO.getText());
                    child.setType(FeatureKindEnum.busiAttr.name());
                    child.setBasicTypeId(businessAttrVO.getBasicTypeId());
                    child.setBasicTypeName(businessAttrVO.getBasicTypeName());
                    child.setBasicTypeLabel(businessAttrVO.getBasicTypeLabel());
                    child.setDisabled(exitBusiAttrIdList.contains(id));         // 已存在将 disabled设置为 true
                    child.setParentId(categoryId);
                    treeNodeVOList.add(child);
                }
            }
        }
        TreeBuilder<BusiAttrTreeNodeVO, String> builder = new TreeBuilder<>();

        return builder.buildTree(treeNodeVOList);
    }


    @Override
    public boolean removeByIds(List<String> ids, String deleteFlag) {
        return businessAttrMapper.updateDeleteFlagByIds(ids, deleteFlag) > 0;
    }
}
